# -*- coding: utf-8 -*-

# 函数式编程已经成为现在编程中的一大趋势，在传统的编程中，方法是不能作为参数进行传递， 但是在函数式编程中，我们可以
# 将函数作为参数进行传递

import math


def sum(x, y):
    return x + y


def nn(n):
    return n * n


def sum_nn(x, y, sum, nn):
    return sum(x, y) + nn(x)


print sum_nn(2, 2, sum, nn)

# map()方法可以对list中的每个元素进行同样的操作
# reduce()方法可以对其中的元素进行累计操作

L1 = ['adam', 'LISA', 'barT']


def normalize(name):
    return str(name).capitalize()


L2 = list(map(normalize, L1))
print L2


# Python提供的sum()函数可以接受一个list并求和，请编写一个prod()函数，可以接受一个list并利用reduce()求积：
def sum_1(nums):
    num = 0
    for x in nums:
        num += x
    return num


print sum_1(range(1, 10))


def prod(nums):
    return reduce(sum, nums)


print prod(range(1, 10))

str_num = '-1234.456'


def trans(str):
    n = 10
    y = 0.1
    index = 1
    sum = 0
    inte = True
    if str[0] == '-':
        n = -10
        y = -0.1
        index = -1
    for i in str:
        if i == '-':
            continue
        if i == '.':
            inte = False
            continue
        if inte:
            sum = sum * n + (int(i) * index)
            n = 10
        else:
            sum += y * int(i)
            y = y / 10.0
    return sum


print trans(str_num)


def su(num):
    for x in range(2, int(math.sqrt(num) + 1)):
        if num % x == 0:
            return False

    return True


print filter(su, range(1, 100))


def compare(x, y):
    if x > y:
        return -1
    elif x == y:
        return 0
    else:
        return 1


print sorted([3, 5, 123, 1], compare)


def count():
    fs = []
    for i in range(1, 5):
        def f(j):
            def g():
                return j * j
            return g
        fs.append(f(i))
    return fs

f1, f2, f3, f4 = count()
print f1()
print f2()
print f3()


# 匿名函数lambada
print map(lambda x : x + 1, range(1, 10))


# 装饰器测试， 这个有点像java中的代理， spring中的aop
def log(func):
    def wrapper(*args, **kw):
        print 'call %s()'% func.__name__
        return func(*args, **kw)
    return wrapper

@log
def print_log():
    print '测试装饰器'

print_log()
# call print_log()
# 测试装饰器